/// Author: Samle
import 'dart:async';
import 'package:flutter/material.dart';
import 'books_element.dart';

/// 自定义列表组件
class BooksListView extends StatefulWidget {

  /// 传入参数
  const BooksListView({
    Key? key,
    required this.datas,         /// 数据列表 [{},{}……]
    this.frontHeight = 50.0,     /// 前置高度，避开搜索栏
    required this.pullup,        /// 上拉回调函数
    required this.dropdown,      /// 下拉回调函数
    required this.onPressed,     /// 点击回调函数
    required this.doublePressed, /// 双击回调函数
    required this.longPressed,   /// 长按回调函数
    required this.onTap,         /// 点击回调函数
    required this.toDetail,      /// 点击回调函数
  }) : super(key: key,);
  final List datas;
  final double frontHeight;
  final ValueChanged<Map> onPressed;
  final ValueChanged<Map> doublePressed;
  final ValueChanged<Map> longPressed;
  final ValueChanged<int> onTap;
  final ValueChanged<int> toDetail;
  final VoidCallback pullup;
  final VoidCallback dropdown;

  @override
  State<StatefulWidget> createState() => BooksListViewState();
}

/// 构建
class BooksListViewState extends State<BooksListView> {

  /// 上拉加载回调函数
  final ScrollController _controller = ScrollController();
  /// 上拉加载更多
  _loadMore() async {
    /// 强制休眠 1 秒
    await Future.delayed(Duration(seconds: 1));
    /// 放入到集合中
    setState(() {widget.pullup();});
    setState((){});
  }

  @override
  void initState() {
    /// 为滚动控制器添加监听
    _controller.addListener(() {
      /// 在加载的时候锁死
      if (_controller.position.pixels == _controller.position.maxScrollExtent) {
        /// 触发上拉加载更多机制
        _loadMore();
      }
    });
    setState((){});
    super.initState();
  }

  @override
  void dispose() {
    /// 销毁 滚动控制器 ScrollController
    _controller.dispose();
    super.dispose();
  }

  buildElementList() {
    List<Widget> elementList = [];
    elementList = [
      SizedBox(height: widget.frontHeight,), /// 前置高度
    ];
    for(var item in widget.datas) {
      elementList.add(
          BooksElement(
            dataForm: item,
            onTap: (){ widget.onTap(item['id']); },
            toDetail: (){ widget.toDetail(item['id']); },
            onPressed: (){ widget.onPressed(item); },
            doublePressed: (){ widget.doublePressed(item); },
            longPressed: (){ widget.longPressed(item); },
          )
      );
    }
    elementList.add(SizedBox(height: 50,));
    return elementList;
  }

  Future<void> _onRefresh() async {
    await Future.delayed(Duration(seconds: 1)); /// 强制休眠 1 秒
    setState(() {widget.dropdown();});
    return;
  }

  @override
  Widget build(BuildContext context) {
    return RefreshIndicator(
      color: Colors.blue,  /// 圆圈进度颜色
      displacement: 50.0,  /// 下拉停止的距离
      backgroundColor: Colors.grey[200],/// 背景颜色
      onRefresh: _onRefresh,
      child: ListView(
        controller: _controller,
        children: buildElementList(),
      ),
    );
  }

}
